package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.sun.org.glassfish.gmbal.ParameterNames;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RequestMapping("/dish")
@RestController
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.savawithFlavor(dishDto);
        return R.success("保存成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //创建DishPageinfo
        Page<Dish> DishpageInfo = new Page<>(page, pageSize);
        //由于页面要显示菜品名称 但是Dish里没有菜品分类名称 因此要创建DishDtoPageInfo
        Page<DishDto> DishDtoPageInfo = new Page<>();
        //创建条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        //查询条件
        queryWrapper.like(name != null, Dish::getName, name);
        //查询
        dishService.page(DishpageInfo, queryWrapper);
        //将PageInfo复制给DishDtoPageInfo
        BeanUtils.copyProperties(DishpageInfo, DishDtoPageInfo, "records");
        //获取PageInfo的records(本质是List<Dish>)对象
        List<Dish> records = DishpageInfo.getRecords();
        //创建List<DishDto> list
        List<DishDto> list=new ArrayList<>();
        //遍历records
        records.forEach((record) -> {
            //创建DishDto 后面将这个对象加入到List<DishDto> list里
            DishDto dishDto = new DishDto();
            //将遍历出来的Dish对象的值 复制给DishDto对象
            BeanUtils.copyProperties(record, dishDto);
            //通过record对象获取分类的id
            Long categoryId = record.getCategoryId();
            //通过获取的id查询获取category对象
            Category category = categoryService.getById(categoryId);
            //将获取的category对象 获取Name 设置进DishDto对象里
            dishDto.setCategoryName(category.getName());
            //放入List<DishDto> list集合里
            list.add(dishDto);
        });
        DishDtoPageInfo.setRecords(list);
        return R.success(DishDtoPageInfo);

    }

//    @GetMapping("/page")
//    public R<Page> page(int page, int pageSize, String name) {
//
//        //创建DishPageinfo
//        Page<Dish> DishpageInfo = new Page<>(page, pageSize);
//        //由于页面要显示菜品名称 但是Dish里没有菜品分类名称 因此要创建DishDtoPageInfo
//        Page<DishDto> DishDtoPageInfo = new Page<>();
//        //创建条件构造器
//        QueryWrapper<Dish> queryWrapper = new QueryWrapper();
//        //查询条件
//        queryWrapper.like(name != null,"name",name);
//
//        queryWrapper.eq("is_delete",0);
//        //查询
//        dishService.page(DishpageInfo, queryWrapper);
//        //将PageInfo复制给DishDtoPageInfo
//        BeanUtils.copyProperties(DishpageInfo, DishDtoPageInfo, "records");
//        //获取PageInfo的records(本质是List<Dish>)对象
//        List<Dish> records = DishpageInfo.getRecords();
//        //创建List<DishDto> list
//        List<DishDto> list=new ArrayList<>();
//        //遍历records
//        records.forEach((record) -> {
//            //创建DishDto 后面将这个对象加入到List<DishDto> list里
//            DishDto dishDto = new DishDto();
//            //将遍历出来的Dish对象的值 复制给DishDto对象
//            BeanUtils.copyProperties(record, dishDto);
//            //通过record对象获取分类的id
//            Long categoryId = record.getCategoryId();
//            //通过获取的id查询获取category对象
//            Category category = categoryService.getById(categoryId);
//            //将获取的category对象 获取Name 设置进DishDto对象里
//            dishDto.setCategoryName(category.getName());
//            //放入List<DishDto> list集合里
//            list.add(dishDto);
//        });
//
//
//        DishDtoPageInfo.setRecords(list);
//
//
//        return R.success(DishDtoPageInfo);
//
//    }


    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getWithFlavor(id);
        return R.success(dishDto);

    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){

        Long id = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach((flavor)->{
            LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId,id);
            dishFlavorService.remove(queryWrapper);
            //flavor.setDishId(id);
        });
        dishFlavorService.saveBatch(flavors);
        dishService.updateById(dishDto);
        return R.success("修改成功");
    }

    @PostMapping("/status/{statu}")
    public R<Integer> changestatu(@PathVariable Integer statu,@RequestParam List<Long> ids){
//        List<Long> list= Arrays.asList(ids);
        List<Dish> dishes = dishService.listByIds(ids);
        dishes.forEach((dish)->{
            dish.setStatus(statu);
        });
        dishService.updateBatchById(dishes);
        return R.success(statu);
    }

    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){

        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.in(DishFlavor::getDishId,ids);
        dishFlavorService.remove(queryWrapper);
//        for (Long id : ids) {
//            queryWrapper.eq(DishFlavor::getDishId,id);
//            dishFlavorService.remove(queryWrapper);
//        }
        dishService.removeByIds(ids);
        return R.success("删除成功");
    }

//    @GetMapping("/list")
//    public R<List<Dish>> getDish(Dish dish){
//        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper();
//        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
//        queryWrapper.eq(Dish::getStatus,1);
//        queryWrapper.orderByDesc(Dish::getCreateTime);
//        List<Dish> list = dishService.list(queryWrapper);
//        return R.success(list);
//    }
    @GetMapping("/list")
    public R<List<DishDto>> getDish(Dish dish){
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper();
        //根据caregoryid获取菜品信息
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //根据创建时间进行排序
        queryWrapper.orderByDesc(Dish::getCreateTime).orderByAsc(Dish::getSort);
        //根据是否在售进行查询 只查询在售
        queryWrapper.eq(Dish::getStatus,1);
        //查询
        List<Dish> list = dishService.list(queryWrapper);
        //因为dish类中没有DishFlavor 所以创建Lish<DishDto>接收
        //遍历查询出来的list
        List<DishDto> Dtolist=list.stream().map((item)->{
            //创建DishDto对象
            DishDto dishDto=new DishDto();
            //将list集合中的Dish对象复制到DishDto对象里
            BeanUtils.copyProperties(item,dishDto);
            //获取分类id
            Long categoryId = item.getCategoryId();
            //根据分类id获取分类名字
            Category category = categoryService.getById(categoryId);
            if (category!=null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper=new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(Dtolist);
    }


//    @DeleteMapping
//    public R<String> delete(Long[] ids){
//        dishService.removeByIds(Arrays.asList(ids));
//        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper();
//        for (Long id : ids) {
//            queryWrapper.eq(DishFlavor::getDishId,id);
//            dishFlavorService.remove(queryWrapper);
//        }
//        return R.success("删除成功");
//    }
}
